const config = require("../mfo.config.js");
const fs = require("fs");
const path = require("path");

const getChoicesURLs = () => {
  return new Promise((resolve, reject) => {
    try {
      let choicesURLs = {};
      const basePath = path.resolve(__dirname, "../baseTemplate/config/");
      if (process.env.CUSTOMCONFIG) {
        const currentPath = process.cwd();
        const currentFile = currentPath + "\\" + process.env.CUSTOMCONFIG;
        fs.exists(currentFile, function (exists) {
          if (exists) {
            choicesURLs = require(currentFile).template;
          } else {
            choicesURLs = require(basePath +
              "/" +
              config.template.url).template;
          }
          resolve(choicesURLs);
        });
      } else {
        choicesURLs = require(basePath + "/" + config.template.url).template;
        resolve(choicesURLs);
      }
    } catch (err) {
      reject(err);
    }
  });
};

/* const choicesURLs = require(process.env.CUSTOMCONFIG ||
  "../" + config.template.url); */

const choicesList = (filter) => {
  return getChoicesURLs()
    .then((choicesURLs) => {
      let listData = [];
      for (let n in choicesURLs) {
        let r = filter(n, choicesURLs);
        r && Object.keys(r).forEach((k) => listData.push({ name: k }));
      }
      return listData;
    })
    .catch((err) => {
      return Promise.reject(err);
    });
};

module.exports = {
  getChoicesURLs,
  choicesList,
};
